package com.atguigu.msmservice.controller;

import com.atguigu.commonutils.R;
import com.atguigu.msmservice.service.MsmService;
import com.atguigu.msmservice.utils.RandomUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName MsmController
 * @Description TODO
 * @Detail detail
 * @Author MyPC
 * @Date 2020/6/23
 * @Version 1.0
 */
@RestController
@RequestMapping("/edumsm/msm")
@EnableDiscoveryClient
//@CrossOrigin
public class MsmController {
    @Autowired
    MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> template;

    /**
     * 发送短信验证码
     * 短信验证码由我们自己生成，而不是阿里云为我们生成
     * 阿里云只负责帮我们发送短信验证码
     * @param phone 手机号
     * @return
     */
    @GetMapping("send/{phone}")
    public R send(@PathVariable("phone") String phone){
        //从redis中获取短信验证码，如果存在，无需再次发送
        String code = template.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return R.ok();
        }
        //如果redis获取不到短信验证码，那么调用阿里云发送短信验证码
        code = RandomUtil.getFourBitRandom();
        Map<String,Object> codeMap=new HashMap<>();
        codeMap.put("code",code);
        boolean isSend=msmService.send(codeMap,phone);
        if(isSend){
            //短信发送成功后，存储短信验证码到redis中,在redis存储5分钟
            template.opsForValue().set(phone,code,5L, TimeUnit.MINUTES);
            return R.ok();
        }else {
            return R.error().message("短信发送失败");
        }
    }
}
